﻿using System.Diagnostics;

namespace HCore
{
    public class StopwatchTimer
    {
        public float currentTime => _frameCount * _frameTime;
        public int frameCount => _frameCount;
        public float timerScale => _timeScale;
        public float deltaTime => _frameTime;
        public float frameRate => _frameRate;
        public float totalTime => _totalTime;

        private int _frameCount;
        private float _frameTime;
        private float _timeScale;
        private float _lastTime;
        private float _totalTime;
        private readonly int _frameRate;
        private readonly Stopwatch _stopwatch;

        public StopwatchTimer(int frameRate)
        {
            _frameRate = frameRate;
            _timeScale = 1;
            _stopwatch = new Stopwatch();
        }

        public void Start()
        {
            _stopwatch.Start();
            _frameTime = 1.0f / _frameRate;
            _frameCount = 0;
            _lastTime = (float) (_stopwatch.ElapsedMilliseconds * 1.0 / 1000);
            _totalTime = 0;
        }

        public bool ReadyForNextFrame()
        {
            float current = (float) (_stopwatch.ElapsedMilliseconds * 1.0 / 1000);
            float delta = (current - _lastTime) * _timeScale;

            _totalTime += delta;
            _lastTime = current;
            if (_totalTime >= _frameCount * _frameTime)
            {
                return true;
            }

            return false;
        }

        public void IntoNextFrame()
        {
            _frameCount++;
        }
    }
}